package com.wy.business.assembly.services;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.wy.business.assembly.pojos.UploadInfo;
import com.wy.component.dataConvert.Base64Image;
import com.wy.component.properties.PropertiesUtil;
import com.wy.framework.services.AbstractBaseService;

/**
 * 
 * 项目名称：openportal_coding
 * 类名称：uploadInfoService
 * 类描述：上传组件service类
 * 创建人：黄忠
 * 创建时间：2016-5-9 上午9:32:54
 * 修改人：黄忠
 * 修改时间：2016-5-9 上午9:32:54
 * 版本信息：@version 1.0
 * Copyright (c) 2016万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version
 */
@Service
public class UploadInfoService extends AbstractBaseService {
	
	private static Logger logger = LoggerFactory.getLogger(UploadInfoService.class);
	
	//原图
	private static String originalPicture = "originalPicture";
	
	//中等图片
	private static String midPicture = "midPicture";
	
	//缩略图片
	private static String thumbnailPictures = "thumbnailPictures";

	/**
	 * 
	 * Function Name               upload                                   
	 * @param uploadInfo
	 * @return          		             
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @description 上传方法
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-5-9 上午9:32:46           黄忠                     Initial
	 **********************************************************************
	 */
	public Map<String,String> upload(UploadInfo uploadInfo) throws FileNotFoundException, IOException {
		
		logger.info("Enter uploadInfoService upload.");
		Map<String,String> result = new HashMap<String,String>();

		if(uploadInfo == null) {
			logger.info("uploadInfoService upload uploadInfo is null.");
			result.put("error", "001");
			return result;
		}
		
		if(StringUtils.isEmpty(uploadInfo.getFileType())) {
			logger.info("uploadInfoService upload uploadInfo.getFileType() is null.");
			result.put("error", "002");
			return result;
		}
		
		//文件路径
		String path = new PropertiesUtil().getAppProperties("fileupload.dir");
		
		//访问路径
		String url = new PropertiesUtil().getAppProperties("internet.url");
		
		SimpleDateFormat year = new SimpleDateFormat("yyyy");
		String yearStr = year.format(new Date());
		SimpleDateFormat month = new SimpleDateFormat("MM");
		String monthStr = month.format(new Date());
		
		String uuid = UUID.randomUUID().toString();
		//上传文件为图片
		if("0".equals(uploadInfo.getFileType())) {
			
			logger.info("uploadInfoService upload uploadInfo.getFileType() == 0,type is image.");
			//图片文件不能为null
			if(StringUtils.isEmpty(uploadInfo.getImgFile())){
				logger.info("uploadInfoService upload imgFile is null.");
				result.put("error", "003");
				return result;
			}
			
			//拼装原图上传路径
			path+="/images/" + yearStr + "/" + monthStr;
			url+="/images/" + yearStr + "/" + monthStr;
			
			String originalPath = path ;
			
			//目录不存在 则创建
			File file = new File(originalPath);
			if(!file.exists()){
				logger.info(originalPath + "   目录不存在，创建目录");
				file.mkdirs(); 
			}
			
			//原图文件名称 uuid

			String fileName = uuid + "-" + originalPicture + ".jpg";
			logger.info("uploadInfoService upload originalPictureName is "+fileName);
			
			originalPath +="/" + fileName;
			logger.info("uploadInfoService upload this file path is "+originalPath);

			//base64上传文件服务器
			Base64Image.GenerateImage(uploadInfo.getImgFile(), originalPath);
			
			//图片大小不能超过限制
			String picSize = new PropertiesUtil().getAppProperties("fileupload.maxSizePic");
			File filePic = new File(originalPath);
			Long maxSize = Long.parseLong(picSize) * 1024;
			if(filePic.length() > maxSize.longValue()) {
				logger.info("uploadInfoService upload imgFile length > 200*1024. 图片过大");
				result.put("error", "004");
				return result;
			}
			
			result.put("originalPath", url + "/" + fileName);
			//压缩图片  中图\
			
			String midPath = path;
			//目录不存在 则创建
			file = new File(midPath);
			if(!file.exists()){
				logger.info(midPath+"    目录不存在，创建此目录");
				file.mkdirs(); 
			}
			
			//中图文件名称 uuid
			String midPictureName = uuid; 
			midPath += "/" + midPictureName+ "-"+ midPicture + ".jpg";
			zipImageFile(originalPath, uploadInfo.getMidImgWidth(), uploadInfo.getMidImgHeight(), uploadInfo.getMidCompressionRatio(), midPath);
			result.put("midPath",  url + "/" + midPictureName+ "-"+ midPicture + ".jpg");
			
			logger.info("uploadInfoService upload this file midPath is "+midPath);
			
			//缩略图
			String thumbnailPath = path  ;
			//目录不存在 则创建
			file = new File(thumbnailPath);
			if(!file.exists()){
				logger.info(thumbnailPath+"    目录不存在，创建此目录");
				file.mkdirs(); 
			}
			
			//缩略图名称 uuid
			String thumbnailPictureName = uuid; 
			
			thumbnailPath += "/" + thumbnailPictureName + "-" + thumbnailPictures + ".jpg";
			zipImageFile(originalPath, uploadInfo.getThumbnailImgWidth(), uploadInfo.getThumbnailHeight(), uploadInfo.getThumbnailCompressionRatio(), thumbnailPath);
			
			result.put("thumbnailPath",  url + "/" + thumbnailPictureName + "-" + thumbnailPictures + ".jpg");
			logger.info("uploadInfoService upload this file thumbnailPath is "+thumbnailPath);
			logger.info("Exit uploadInfoService upload.");
			return result;
		} else {
			
			logger.info("uploadInfoService upload 上传文件");
			File file = uploadInfo.getOtherFile();
			
			//判断文件是否为null
			if(file == null || file.length() == 0) {
				logger.info("uploadInfoService upload otherFile is null.");
				result.put("error", "005");
				return result;
			}
			
			//判断文件大小
			String fileSize = new PropertiesUtil().getAppProperties("fileupload.maxSizeFile");
			Long maxSize = Long.parseLong(fileSize) * 1024;
			if(file.length() > maxSize.longValue()) {
				logger.info("uploadInfoService upload fileSize length > 2048*1024. 文件过大");
				result.put("error", "006");
				return result;
			}
			
			//拼装原图上传路径
			path+="/files/" + yearStr + "/" + monthStr;
			url+="/files/" + yearStr + "/" + monthStr;
			
			//目录不存在 则创建
			File fileCatagroy = new File(path);
			if(!fileCatagroy.exists()){
				logger.info(path + "   目录不存在，创建目录");
				fileCatagroy.mkdirs(); 
			}
			String fileType = uploadInfo.getFileName().substring(uploadInfo.getFileName().indexOf("."), uploadInfo.getFileName().length());
			String fileName = uuid + fileType; 
			
			String targerFile = path + "/" + fileName ;
			fileCatagroy = new File(targerFile);
			FileUtils.copyFile(file,fileCatagroy );
			result.put("filePath", url + "/" + fileName);
			logger.info("文件上传完成 path = "+ url + "/" + fileName);
			logger.info("Exit uploadInfoService upload.");
			return result;
		}
		
		
		
	}
	
	
	/**
	  * 直接指定压缩后的宽高：
	  * (先保存原文件，再压缩、上传)
      * @param oldFile 要进行压缩的文件全路径
      * @param width 压缩后的宽度
      * @param height 压缩后的高度
      * @param quality 压缩质量
      * @param smallIcon 文件名的小小后缀(注意，非文件后缀名称),入压缩文件名是yasuo.jpg,则压缩后文件名是yasuo(+smallIcon).jpg
      * @return 返回压缩后的文件的全路径
      
      */
	
	 public String zipImageFile(String oldFile, int width, int height,float quality, String newPath) {
	
	        if (oldFile == null) {
	            return null;
	        }
	        
	        String newImage = null;
	
	        try {
	            /**对服务器上的临时文件进行处理 */
	            Image srcFile = ImageIO.read(new File(oldFile));
	            /** 宽,高设定 */
	            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	            tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
	            String filePrex = oldFile.substring(0, oldFile.indexOf('.'));
	            /** 压缩后的文件名 */
	            newImage = newPath;
	            /** 压缩之后临时存放位置 */
	            FileOutputStream out = new FileOutputStream(newImage);
	            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
	            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
	            /** 压缩质量 */
	            jep.setQuality(quality, true);
	            encoder.encode(tag, jep);
	            out.close();
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        return newImage;
	    }
	 
	    /**
	     * 保存文件到服务器临时路径(用于文件上传)
	     * @param fileName
	     * @param is
	     * @return 文件全路径
	     */
	    public static String writeFile(String fileName, InputStream is) {
	        if (fileName == null || fileName.trim().length() == 0) {
	            return null;
	        }
	        try {
	            /** 首先保存到临时文件 */
	            FileOutputStream fos = new FileOutputStream(fileName);
	            byte[] readBytes = new byte[512];// 缓冲大小
	            int readed = 0;
	            while ((readed = is.read(readBytes)) > 0) {
	                fos.write(readBytes, 0, readed);
	            }
	            fos.close();
	            is.close();
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        return fileName;
	    }
	 
	    /**
	     * 等比例压缩算法：
	     * 算法思想：根据压缩基数和压缩比来压缩原图，生产一张图片效果最接近原图的缩略图
	     * @param srcURL 原图地址
	     * @param deskURL 缩略图地址
	     * @param comBase 压缩基数
	     * @param scale 压缩限制(宽/高)比例  一般用1：
	     * 当scale>=1,缩略图height=comBase,width按原图宽高比例;若scale<1,缩略图width=comBase,height按原图宽高比例
	     * @throws Exception
	     * @author shenbin
	     * @createTime 2014-12-16
	     * @lastModifyTime 2014-12-16
	     */
	    public static void saveMinPhoto(String srcURL, String deskURL, double comBase,
	            double scale) throws Exception {
	        File srcFile = new java.io.File(srcURL);
	        Image src = ImageIO.read(srcFile);
	        int srcHeight = src.getHeight(null);
	        int srcWidth = src.getWidth(null);
	        int deskHeight = 0;// 缩略图高
	        int deskWidth = 0;// 缩略图宽
	        double srcScale = (double) srcHeight / srcWidth;
	        /**缩略图宽高算法*/
	        if ((double) srcHeight > comBase || (double) srcWidth > comBase) {
	            if (srcScale >= scale || 1 / srcScale > scale) {
	                if (srcScale >= scale) {
	                    deskHeight = (int) comBase;
	                    deskWidth = srcWidth * deskHeight / srcHeight;
	                } else {
	                    deskWidth = (int) comBase;
	                    deskHeight = srcHeight * deskWidth / srcWidth;
	                }
	            } else {
	                if ((double) srcHeight > comBase) {
	                    deskHeight = (int) comBase;
	                    deskWidth = srcWidth * deskHeight / srcHeight;
	                } else {
	                    deskWidth = (int) comBase;
	                    deskHeight = srcHeight * deskWidth / srcWidth;
	                }
	            }
	        } else {
	            deskHeight = srcHeight;
	            deskWidth = srcWidth;
	        }
	        BufferedImage tag = new BufferedImage(deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR);
	        tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeight, null); //绘制缩小后的图
	        FileOutputStream deskImage = new FileOutputStream(deskURL); //输出到文件流
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(deskImage);
	        encoder.encode(tag); //近JPEG编码
	        deskImage.close();
	    }
	 
       // ImageCompressUtil.zipImageFile("f:/食尸鬼 - 藿香.jpg", 1280, 1280, 1f, "x2");
       // ImageCompressUtil.saveMinPhoto("f:/食尸鬼 - 藿香.jpg", "f:/11.jpg", 139, 0.9d);

}
